<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/2
 * Time: 08:39
 */

namespace app\index\logic;


use app\admin\logic\MoneyLogic;
use app\common\model\Page;
use app\common\utils\Constant;
use think\Db;
use think\Exception;

class WithdrawLogic
{
    /**
     * 提现操作
     * @param $money float 提现金额
     * @param $user_id int 用户id
     * @return array status 0失败 1成功 2校验失败 3余额不足
     */
    public function withdrawal($money,$user_id){
        Db::startTrans();
        try{
            if(empty($money) || !is_numeric($money) || $money <0){
                return array('status'=>2,'msg'=>'请输入正确的金额！');
            }
            $result = $this->check($money,$user_id);
            if($result['status'] != 1){
                return $result;
            }
            $withdrawal_poundage = $this->getConfigByName(Constant::CONFIG_NAME_WITHDRAWAL_POUNDAGE);//提现手续费
            $poundage_money = $money * $withdrawal_poundage;
            $balance = model('User')->where(array('id'=>$user_id))->value('balance');
            if($balance < $money){
                return array('status'=>3,'msg'=>'余额不足！');
            }
            model('User')->where(array('id'=>$user_id))->setDec('balance',$money);
            $this->saveWithdrawLog($money-$poundage_money ,$poundage_money,$user_id);
            $this->saveMoneyLog($money,$user_id);
            Db::commit();
            return array('status'=>1);
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }
//        model('User')
    }

    /**
     * 获取提现记录列表
     * @param $data
     * @return mixed
     */
    public function getWithdrawLogList($data){
        $map = [];
        if(!isset($data['page_size'])){
            $data['page_size'] = 10;
        }
        if(!isset($data['page_num'])){
            $data['page_num'] = 1;
        }
        if(isset($data['user_id']) && !empty($data['user_id'])){
            $map['user_id'] = $data['user_id'];
        }
        if(isset($data['status'])){
            $map['status'] = $data['status'];
        }
        $result = $this->queryByMap($map,$data['page_num'],$data['page_size']);
        return $result;
    }

    private function queryByMap($map,$page_num,$page_size){
        $startno = ($page_num - 1) * $page_size;
        $list = model('WithdrawLog')
            ->where($map)
            ->limit($startno,$page_size)
            ->order('id','desc')
            ->select();
        $count = model('WithdrawLog')
            ->where($map)
            ->count();
        $result['list'] = $list;
        $page = new Page($page_num,$count,$page_size);
        $result['page'] = $page;
        return $result;
    }

    private function check($money,$user_id){
        $highest_limit = $this->getConfigByName(Constant::CONFIG_NAME_HIGHEST_LIMIT);//最高提现额度
        $lowest_limit = $this->getConfigByName(Constant::CONFIG_NAME_LOWEST_LIMIT);//最低提现额度
        $withdrawal_limit = $this->getConfigByName(Constant::CONFIG_NAME_WITHDRAWAL_LIMIT);//每日提现次数
        if($money > $highest_limit){
            return array('status'=>2,'msg'=>'最高提现额度为'.$highest_limit.'！');
        }
        if($money < $lowest_limit){
            return array('status'=>2,'msg'=>'最低提现额度为'.$lowest_limit.'！');
        }
        $begin_today=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end_today=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $map['user_id'] = $user_id;
        $count = model('WithdrawLog')
            ->where($map)
            ->whereTime('create_time', 'between', [$begin_today, $end_today])
            ->count();
        if($count >= $withdrawal_limit){
            return array('status'=>2,'msg'=>'每日最多提现次数为'.$withdrawal_limit.'，您今日无法提现！');
        }
        return array('status'=>1);
    }


    private function getConfigByName($name){
        $value = model('Config')->where(array('name'=>$name))->value('value');
        return $value;
    }

    private function saveWithdrawLog($money,$poundage,$user_id){
        $log['money'] = $money;
        $log['poundage'] = $poundage;
        $log['status'] = Constant::VERIFY_STATUS_WAIT;//等待审核
        $log['create_time'] = time();
        $log['user_id'] = $user_id;
        $log['desc'] = '';
        model('WithdrawLog')->insert($log);
    }

    private function saveMoneyLog($money,$user_id){
        $change_type = Constant::CHANGE_TYPE_WITHDRAWAL;
        $money_type = Constant::MONEY_TYPE_BALANCE;
        $in_out_type = Constant::IN_OUT_TYPE_OUT;
        $desc = '用户提现，扣除余额';
        $map['id'] = $user_id;
        $current_money = model('User')->where($map)->value('balance');
        $logic = new MoneyLogic();
        $logic->saveMoneyLog($money,$current_money,$change_type,
            $in_out_type,$desc,$user_id,$money_type,0);
    }
}